<template>
  <div class="app-container">
      <el-row :gutter="24">
          <el-col :span="24" :xs="24">
              <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
                  <el-form-item label="用户名称" prop="nickname">
                      <el-input v-model="queryParams.nickname" placeholder="请输入" clearable style="width: 240px" maxlength="30"
                          @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="用户账号" prop="account">
                      <el-input v-model="queryParams.account" placeholder="请输入" clearable style="width: 240px" maxlength="30"
                          @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item style="margin-left: 40px;">
                      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                      <el-button type="success" icon="Plus" @click="handleAdd">新增</el-button>
                  </el-form-item>
              </el-form>

              <!-- <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd"
                            v-hasPermi="['system:user:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                            v-hasPermi="['system:user:edit']">修改</el-button>
                    </el-col> 
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                            v-hasPermi="['system:user:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="Upload" @click="handleImport"
                            v-hasPermi="['system:user:import']">导入</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport"
                            v-hasPermi="['system:user:export']">导出</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
                </el-row> -->

              <el-table v-loading="loading" :data="userData"  @selection-change="handleSelectionChange"
                  style="margin-top: 10px;margin-left: 20px;margin-right: 20px;width: calc(100% - 40px);">
                  <el-table-column type="index" width="50" label="编号" />
                  <el-table-column label="用户名称" align="center" prop="nickname" />
                  <el-table-column label="用户账号" align="center" prop="account" />
                  <el-table-column label="登录密码" align="center" prop="password" />
                  <el-table-column label="角色" align="center" prop="roleNameList" />
                  <el-table-column label="用户说明" align="center" prop="remark" />
                  <el-table-column label="创建时间" align="center" prop="createTime" />
                  <el-table-column label="操作" fixed="right" align="center" width="230"
                      class-name="small-padding fixed-width">
                      <template #default="scope">
                          <el-button link type="success" @click="handleLook(scope.row)">查看</el-button>
                          <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                          <el-button link type="primary" @click="handleResetting(scope.row)">重置密码</el-button>
                          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
              <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                  @pagination="getList" style="margin-right: 20px;" />
          </el-col>
      </el-row>

      <!-- 添加 -->
      <el-dialog v-model="open" width="600px" append-to-body :title="getDialogTitle()">
          <div v-loading="dialogloading">
              <el-form :model="form" :rules="rules" ref="userRef" label-width="120px">
                  <el-form-item label="用户名称" prop="nickname">
                      <!-- <el-input v-model="form.nickname" remote-method :readonly="dialogType == 3" placeholder="请输入" style="width: 400px" maxlength='11' /> -->
                      <el-select v-model="form.nickname" :disabled="dialogType == 3" placeholder="请选择" clearable style="width: 400px">
                          <el-option v-for="item in optionsUser" :key="item.id" :label="item.name" :value="item.name" />
                      </el-select>
                  </el-form-item>
                  <el-form-item label="用户账号" prop="account">
                      <el-input v-model="form.account" :readonly="dialogType == 3" placeholder="请输入" style="width: 400px" maxlength='11' />
                  </el-form-item>
                  <el-form-item label="角色" prop="roleNameList">
                      <el-select v-model="form.roleNameList" multiple :disabled="dialogType == 3" placeholder="请选择"  clearable style="width: 400px">
                          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                  </el-form-item>
                  <el-form-item label="登录密码" prop="password">
                      <el-input v-model="form.password" :readonly="dialogType == 3" placeholder="请输入" style="width: 400px" maxlength='11' />
                  </el-form-item>
                 
                  <el-form-item label="用户说明" prop="remark">
                      <el-input v-model="form.remark" :readonly="dialogType == 3" placeholder="请输入" :autosize="{ minRows: 2, maxRows: 4 }"
                          type="textarea" style="width: 400px" maxlength='200' show-word-limit />
                  </el-form-item>
              </el-form>
              <div class="dialog-footer">
                  <el-button type="primary" @click="saveForm">{{ getDialogBtnTitle() }}</el-button>
                  <el-button @click="cancel">取 消</el-button>
              </div>
          </div>
      </el-dialog>
  </div>
</template>

<script setup>
import { apiMdmUserList, apiMdmUserCreate, apiMdmUserUpdate, apiMdmUserDelete, apiRoleList, apiMdmUserDetail, apiRegisterList } from "@/api/authority";

const { proxy } = getCurrentInstance();

const userData = ref([]);
const options = ref([]);
const optionsUser = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const loading = ref(false);
const open = ref(false);
const dialogloading = ref(false);
const total = ref(0);
const dialogType = ref(1)

const data = reactive({
  form: {
    nickname:'',
    account:'',
    password:'',
    remark:'',
    roleNameList:[]
  },
  queryParams: {
      pageNum: 1,
      pageSize: 10,
  },
  rules: {
      nickname: [{ required: true, message: "请输入", trigger: "change" }],
      account: [{ required: true, message: "请输入", trigger: "blur" }],
      password: [{ required: true, message: "请输入", trigger: "blur" }],
      roleNameList: [{ required: true, message: "请选择", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
const getList = () => {
  loading.value = true;
  apiMdmUserList(queryParams.value).then(res => {
      loading.value = false;
      if (res.data) {
          userData.value = res.data.records;
          total.value = res.data.total;
      } else {
          userData.value = []
          total.value = 0
      }
  }).catch(err => {
      loading.value = false
      userData.value = []
      total.value = 0
  });
};

getList();

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
};


/** 重置操作表单 */
function reset() {
  form.value = {
      nickname: [],
      account: undefined,
      password: undefined,
      roleNameList: [],
      remark: undefined
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialogType.value = 1
  form.value = {}
  getType()
  getRegisterList()
  rules.value = {
      nickname: [{ required: true, message: "请输入", trigger: "change" }],
      account: [{ required: true, message: "请输入", trigger: "blur" }],
      password: [{ required: true, message: "请输入", trigger: "blur" }],
      roleNameList: [{ required: true, message: "请选择", trigger: "blur" }],
  }
  openAndClearForm()
};

const handleEdit = (row) => {
  rules.value = {
      nickname: [{ required: true, message: "请输入", trigger: "change" }],
      account: [{ required: true, message: "请输入", trigger: "blur" }],
      password: [{ required: true, message: "请输入", trigger: "blur" }],
      roleNameList: [{ required: true, message: "请选择", trigger: "blur" }],
  }
  reset();
  dialogType.value = 2
  form.value = row
  getType()
  getRegisterList()
  openAndClearForm()
};

/** 用户下拉框 */
const getRegisterList = () => {
    apiRegisterList().then(res => {
        if (res.data) {
          optionsUser.value = res.data
        }
    }).catch(err => { });
};

/** 角色下拉框 */
const getType = () => {
    apiRoleList().then(res => {
        if (res.data) {
           options.value = res.data
        }
    }).catch(err => { });
};

const saveForm = () => {
  proxy.$refs["userRef"].validate(valid => {
      if (valid) {
          dialogloading.value = true;
          if (dialogType.value === 3) {
            dialogloading.value = false;
            open.value = false;
            return
          }
          optionsUser.value.map((v) => {
                if (form.value.nickname === v.name) {
                    form.value.staffId = v.id
                }
          })
          form.value.roleId = form.value.roleNameList
          delete form.value.roleNameList
          if (form.value.id) {
            apiMdmUserUpdate(form.value).then(res => {
                  dialogloading.value = false;
                  proxy.$modal.msgSuccess("操作成功");
                  open.value = false;
                  getList()
              }).catch(err => {
                  dialogloading.value = false
              });
          } else {
            apiMdmUserCreate(form.value).then(res => {
                  dialogloading.value = false;
                  proxy.$modal.msgSuccess("操作成功");
                  open.value = false;
                  getList()
              }).catch(err => {
                  dialogloading.value = false
              });
          }
      }
  })
};

//详情
const handleLook = (row) => {
    loading.value = true;
    apiMdmUserDetail(row.id).then(res => {
        loading.value = false;
        if (res.data) {
            form.value = res.data
            dialogType.value = 3
            rules.value = {}
            openAndClearForm()
        }
    }).catch(err => {
        loading.value = false;
    });
}

const openAndClearForm = () => {
    open.value = true
    proxy.$refs["userRef"].clearValidate();
 }

const getDialogTitle = (row) => {
    if (dialogType.value == 1) {
        return '新增'
    } else if (dialogType.value == 2) {
        return '编辑'
    }
    return '详情'
}
const getDialogBtnTitle = () => {
    if (dialogType.value == 1) {
        return '保存'
    } else if (dialogType.value == 2) {
        return '提交'
    }
    return '详情'
}

/** 选择条数  */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.userId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
};

/** 重置密码  */
function  handleResetting(row) {
    proxy.$modal.msgError("请联系管理员");
}

const handleDelete = (row) => {
  proxy.$modal.confirm('是否确认删除该数据项？').then(() => {
      return apiMdmUserDelete(row.id)
  }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

</script>


<style lang="scss" scoped>
.dialog-item-title {
  color: #000;
  font-size: 17px;
  padding-left: 10px;
  margin: 0 20px;
  border-left: 4px #00BFFF solid;
}

.now-select-txt {
  font-size: 15px;
  color: #fff;
  background: #00BFFF;
  padding: 10px 20px;
  border-radius: 10px 10px 0 0;

  span {
      font-size: 20px;
      font-weight: bold;
      margin: 0 10px;
  }

  div {
      cursor: pointer;
      margin-left: 30px;
      font-weight: bold;
  }
}
</style>